import express from 'express';
import { body, validationResult, query, param } from 'express-validator';
import { Order, Domain, Expert, UserQuota } from '../../models/index.js';
import { authenticateMobileUser } from '../../middleware/auth.js';
import { catchAsync, BusinessError, NotFoundError } from '../../middleware/errorHandler.js';
import { success, paginated } from '../../utils/response.js';
import config from '../../config/index.js';

const router = express.Router();

// 用户创建订单
router.post('/create',
  authenticateMobileUser,
  [
    body('quota_type')
      .isIn(['general', 'domain', 'expert'])
      .withMessage('额度类型必须是general、domain或expert'),
    body('target_id')
      .optional()
      .isInt({ min: 1 })
      .withMessage('目标ID必须是正整数'),
    body('purchase_count')
      .isInt({ min: 1, max: 1000 })
      .withMessage('购买次数必须在1-1000之间')
  ],
  catchAsync(async (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      throw new BusinessError('参数验证失败', errors.array());
    }

    const { quota_type, target_id, purchase_count } = req.body;
    const userId = req.user.id;

    let unitPrice = 0;
    let targetInfo = null;

    // 验证目标ID的有效性并计算单价
    if (quota_type === 'general') {
      // 通用额度使用基础价格
      unitPrice = config.pricing.basePrice;
    } else if (quota_type === 'domain') {
      if (!target_id) {
        throw new BusinessError('领域额度必须指定target_id');
      }
      const domain = await Domain.findByPk(target_id);
      if (!domain || !domain.is_enabled) {
        throw new BusinessError('指定的领域不存在或已禁用');
      }
      targetInfo = domain;
      unitPrice = config.pricing.domainPrice;
    } else if (quota_type === 'expert') {
      if (!target_id) {
        throw new BusinessError('专家额度必须指定target_id');
      }
      const expert = await Expert.findByPk(target_id);
      if (!expert || !expert.is_enabled) {
        throw new BusinessError('指定的专家不存在或已禁用');
      }
      targetInfo = expert;
      // 专家额度使用专家自定义价格，如果没有则使用默认价格
      // pricing是JSON数组，取第一个定价配置的价格，如果没有则使用默认价格
      const expertPricing = expert.pricing && expert.pricing.length > 0 ? expert.pricing[0] : null;
      unitPrice = expertPricing?.price || config.pricing.expertDefaultPrice;
    }

    // 计算总金额
    const totalAmount = (unitPrice * purchase_count).toFixed(2);

    // 创建订单
    const order = await Order.createOrder({
      user_id: userId,
      quota_type,
      target_id: quota_type === 'general' ? null : target_id,
      purchase_count,
      amount: parseFloat(totalAmount),
      status: 'pending'
    });

    res.json(success({
      order: {
        ...order.toJSON(),
        unit_price: unitPrice,
        target_info: targetInfo ? {
          id: targetInfo.id,
          name: targetInfo.name || targetInfo.nickname,
          type: quota_type
        } : null
      }
    }, '订单创建成功'));
  })
);

// 获取用户订单列表
router.get('/my-orders',
  authenticateMobileUser,
  [
    query('page').optional().isInt({ min: 1 }).withMessage('页码必须是正整数'),
    query('limit').optional().isInt({ min: 1, max: 50 }).withMessage('每页数量必须在1-50之间'),
    query('status').optional().isIn(['pending', 'paid', 'cancelled', 'refunded']).withMessage('状态参数无效')
  ],
  catchAsync(async (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      throw new BusinessError('参数验证失败', errors.array());
    }

    const { page = 1, limit = 20, status } = req.query;
    const userId = req.user.id;
    
    const result = await Order.getUserOrders(userId, {
      page: parseInt(page),
      limit: parseInt(limit),
      status
    });
    
    res.json(paginated(result.rows, {
      page: parseInt(page),
      limit: parseInt(limit),
      total: result.count,
      pages: Math.ceil(result.count / parseInt(limit))
    }, '获取用户订单成功'));
  })
);

// 获取订单详情
router.get('/:orderNo',
  authenticateMobileUser,
  [
    param('orderNo').notEmpty().withMessage('订单号不能为空')
  ],
  catchAsync(async (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      throw new BusinessError('参数验证失败', errors.array());
    }

    const { orderNo } = req.params;
    const userId = req.user.id;
    
    const order = await Order.findByOrderNo(orderNo);
    if (!order) {
      throw new NotFoundError('订单不存在');
    }
    
    if (order.user_id !== userId) {
      throw new BusinessError('只能查看自己的订单');
    }
    
    res.json(success({
      order
    }, '获取订单详情成功'));
  })
);

// 取消订单
router.post('/:orderNo/cancel',
  authenticateMobileUser,
  [
    param('orderNo').notEmpty().withMessage('订单号不能为空')
  ],
  catchAsync(async (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      throw new BusinessError('参数验证失败', errors.array());
    }

    const { orderNo } = req.params;
    const userId = req.user.id;
    
    const order = await Order.findByOrderNo(orderNo);
    if (!order) {
      throw new NotFoundError('订单不存在');
    }
    
    if (order.user_id !== userId) {
      throw new BusinessError('只能取消自己的订单');
    }
    
    if (order.status !== 'pending') {
      throw new BusinessError('只能取消待支付的订单');
    }
    
    if (order.isExpired()) {
      throw new BusinessError('订单已过期');
    }
    
    order.status = 'cancelled';
    await order.save();
    
    res.json(success({
      order
    }, '订单取消成功'));
  })
);



export default router;
